import React, { Component } from 'react';
import { Modal, Table, Select, Space, Tooltip, Button, message } from 'antd';
import { getAnalysePageConfig, getCategoryTree, getChartComponent, updateAnalysePageConfig } from 'src/services/AnalyseManage';
import { BarChartOutlined, PieChartOutlined, PlusCircleOutlined } from '@ant-design/icons';
import styles from './index.module.scss';
import ViewChart from './ViewChart';
import { RouteComponentProps, withRouter } from 'react-router-dom';

const { Option } = Select;

interface LibaryProps {
	visible: any;
	cancelHandle: Function;
	data?: Array<Object>;
	pageId: string;
	reloadData: Function;
}

interface listItemType {
	name: string;
	id: string;
	effect: string;
	isFile: boolean;
}

interface OperateProps {
	record: listItemType;
	handleView: ( item: any ) => void;
	addDashbord: ( item: any ) => void;
}

const OperateComponent = React.memo( ( props: OperateProps ) => {
	return (
		<Space size="middle">
			{!props.record.isFile && <>
				<Tooltip placement="topRight" title="查看">
					<Button
						type="text"
						icon={<span className={`iconfont bdhchakanxiangqing ${styles.green_btn}`}></span>}
						onClick={() => props.handleView( props.record )}
					></Button>
				</Tooltip>
				<Tooltip placement="topRight" title="添加至仪表板">
					<Button
						type="text"
						icon={<PieChartOutlined className={styles.green_btn} />}
						onClick={() => {
							props.addDashbord( props.record );
						}}
					></Button>
				</Tooltip>
			</>}
		</Space>
	);
} );
OperateComponent.displayName = 'OperateComponent';

class SelectLibaryModal extends Component<LibaryProps & RouteComponentProps> {
	state = {
		selectValue: null,
		fileData: null,
		selectList: [],
		tableData: [],

		page: 1,
		pageSize: 10,
		total: 0,

		// 查看详细信息
		viewVisable: false,
		detailData: {},

		// 当前的 需要添加至仪表盘的 config
		currentConfigs: [],

		selectedRowKeys: [],
		selectedRows: []
	}

	//	列表表头配置
	columns = [
		{
			title: '报表名称',
			dataIndex: 'name',
			render: ( text, record ) => {
				let icon;
				const paddingLeft = record.isFile ? 0 : '24px';
				if ( record.isFile ) {
					icon = <span className={'iconfont bdhwenjianjiadakai'}></span>;
				} else {
					icon = <BarChartOutlined className={styles.green_btn} />;
				}
				return (
					<div style={{ paddingLeft }}>
						{icon}
						<span style={{ marginLeft: '10px' }}>{record.name}</span>
					</div>
				);
			},
		},
		{
			title: '描述',
			dataIndex: 'describe',
		},
		{
			title: '操作',
			key: 'action',
			render: ( record: listItemType ) => (
				<OperateComponent
					record={record}
					addDashbord={( config ) => {
						console.log( config );
						this.handleAddToPanel( [ config.content ] );
					}}
					handleView={( item ) => this.handleView( true, item )}
				></OperateComponent>
			),
		},
	];

	componentDidMount() {
		this.loadChartsDatas();
	}

	// 批量添加至仪表板
	handleBacthAddToPanel = async () => {
		const configs = this.state.selectedRows.map( ( v ) => {
			return v.content;
		} );
		this.handleAddToPanel( configs );
	};

	// 添加至仪表板
	handleAddToPanel = ( configs ) => {
		console.log( configs );
		this.setState( { currentConfigs: configs }, () => {
			this.originSaveHandle();
		} );
	};

	//	新添加的组件，获取y轴最大值
	getMaxY = ( layoutConfig ) => {
		if ( layoutConfig.length === 0 ) return 0;
		let maxY = 0;

		layoutConfig.forEach( ( v ) => {
			maxY = v.y + v.h > maxY ? v.y + v.h : maxY;
		} );
		return maxY;
	};

	originSaveHandle = async () => {
		// console.log( this.props.match.params.editType );
		const { editType } = this.props.match.params as any;
		// 如果是选择原有仪表板，则需要先请求原有的config, 添加后，再保存
		const { currentConfigs } = this.state;
		let response = await getAnalysePageConfig( { pageId: this.props.pageId, type: editType } );
		if ( response.data && response.data.success && response.data.data ) {
			const pageConfigs = JSON.parse( response.data.data.content );
			const { children: originChildren = [], layoutConfig = [] } = pageConfigs;

			let newChildren = originChildren,
				newLayoutConfig = layoutConfig,
				isRepeat = false;
			for ( let k in currentConfigs ) {
				const v = currentConfigs[k];
				if ( originChildren.some( ( i ) => i.key === v.key ) ) {
					// 所选报表中如果存在该图形，提示用户已有该图形
					isRepeat = true;
					message.warning( '所选图表中已存在该图形' );
					break;
				} else {
					let newComponentLayout = {
						i: v.key,
						x: 0,
						y: this.getMaxY( newLayoutConfig ),
						w: 17,
						h: 18,
					};

					newLayoutConfig.push( newComponentLayout );
					newChildren.push( v );
				}
			}

			if ( !isRepeat ) {
				let newPageConfigs = {
					page: {
						...pageConfigs.page,
					},
					children: [ ...newChildren ],
					layoutConfig: [ ...newLayoutConfig ],
				};
				this.saveConfig( response.data.data, newPageConfigs );
			}
		}
	};

	// 保存config
	saveConfig = async ( pageConfig, content ) => {
		let response;
		let data = { id: pageConfig.id, content: JSON.stringify( content ) };
		response = await updateAnalysePageConfig( data );
		console.log( content );

		if ( response.data && response.data.success && response.data.data ) {
			message.success( '保存成功' );
			this.setState( { currentConfigs: [] } );
			this.props.reloadData();
			this.props.cancelHandle();
		}
	};

	handleView = ( visiable, item? ) => {
		this.setState( { viewVisable: visiable, detailData: item } );
	};

	handleChange = ( value ) => {
		const fileData = this.state.selectList.find( t => t.id === value );
		this.setState( {
			fileData: { ...fileData, isFile: true },
			selectValue: value,
		}, () => {
			this.getList();
		} );
	}

	handleSelectionChange = ( selectedRowKeys, selectedRows ) => {
		this.setState( { selectedRowKeys, selectedRows } );
	};

	//	切换页码
	handlePageChange = ( pageNumber: number ) => {
		this.setState(
			{
				page: pageNumber,
			},
			() => {
				this.getList();
			}
		);
	};

	//	修改每页数量
	setPageSize = ( size: number ) => {
		this.setState( {
			pageSize: size,
		} );
	};

	loadChartsDatas = async () => {
		let response: any = {};
		response = await getCategoryTree( { type: 'COMPONENT' } );
		if ( response.data && response.data.success ) {
			if ( response.data.data.length > 0 ) {
				const fileData = { ...response.data.data[0], isFile: true };
				this.setState(
					{
						selectList: response.data.data || [],
						fileData,
						selectValue: fileData.id
					},
					() => {
						this.getList();
					}
				);
			}
		}
	};

	// 请求所有图形数据
	getList = async () => {
		const params = {
			parentId: this.state.selectValue,
			page: this.state.page,
			size: this.state.pageSize,
		};
		let response = await getChartComponent( params );
		if ( response.data && response.data.success ) {
			const row = response.data.data.rows || [];
			const initData = this.state.page === 1 ? [ this.state.fileData, ...row ] : row;

			const data = initData.map( ( item, index ) => {
				return {
					...item,
					content: item.content ? JSON.parse( item.content ) : '',
					key: index,
				};
			} );
			this.setState( { tableData: data, total: response.data.data.total || 0 } );
		}
	}

	render() {
		let { visible, cancelHandle } = this.props;
		return (
			<>
				<Modal
					title="选择指标库"
					visible={visible}
					width="50%"
					onCancel={() => cancelHandle()}
					onOk={() => cancelHandle()}
					footer={
						[] // 设置footer为空，去掉 取消 确定默认按钮
					}
				>
					<div className={styles.top_tools}>
						<Select value={this.state.selectValue} style={{ width: 200 }} onChange={this.handleChange}>
							{
								this.state.selectList.map( t => {
									return <Option key={t.id} value={t.id}>
										{t.name}
									</Option>;
								} )
							}
						</Select>
						<Button type="primary" icon={<PlusCircleOutlined />} onClick={this.handleBacthAddToPanel}>
							批量添加至仪表板</Button>
					</div>
					<div>
						<Table
							childrenColumnName="null"
							scroll={{ x: '100%' }}
							tableLayout="fixed"
							columns={this.columns}
							dataSource={this.state.tableData}
							bordered={true}
							rowKey={( row: listItemType ) => row.id}
							size="middle"
							rowSelection={{ type: 'checkbox', onChange: this.handleSelectionChange }}
							pagination={{
								showSizeChanger: true,
								pageSize: this.state.pageSize,
								total: this.state.total,
								onChange: this.handlePageChange,
								onShowSizeChange: ( current, size ) => this.setPageSize( size ),
								showTotal: ( total ) => `共 ${total} 条`,
							}}
						/>
					</div>
					{/* 查看图形 */}
					{this.state.viewVisable && (
						<ViewChart
							data={this.state.detailData}
							modalVisible={this.state.viewVisable}
							handleCancel={() => this.handleView( false, {} )}
						></ViewChart>
					)}
				</Modal>
			</>
		);
	}
}

export default withRouter( SelectLibaryModal );
